#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

// 初始化
void SLInit(SL* ps)
{
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

// 尾插
// 对于扩容来说
// 1.一次扩充一个空间，程序执行效率低下
// 2.一次扩容固定个大小的空间，小了容易频繁扩容，大了造成空间浪费
// 3.成倍数的增加，可以选择，realloc

void SLCheckCapacity(SL* ps)
{

	if (ps->capacity == ps->size)
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(ps->arr, newCapacity * sizeof(SLDataType));

		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		// 扩容成功
		ps->arr = tmp;
		ps->capacity = newCapacity;

	}
}

void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps != NULL);
	/*if (ps == NULL) return;*/
	// 空间不够，扩容
	// 注意初始化为0
	SLCheckCapacity(ps);

	// 空间足够，直接插入
	ps->arr[ps->size++] = x;
	// ps->size++;
}

void SLPushFront(SL* ps, SLDataType x)
{
	// 判断是否扩容
	SLCheckCapacity(ps);

	// 旧数据往后挪动一位
	for (int i = ps->size; i > 0; i--) {
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	ps->size++;

}

void SLPopBack(SL* ps)
{
	assert(ps != NULL);
	assert(ps->size != NULL);

	// 顺序表不为空
	ps->size--;
}

void SLPopFront(SL* ps)
{
	assert(ps != NULL);
	assert(ps->size != NULL);

	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps != NULL);
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);

	// pos之后的数据往后挪动一位，pos空出来
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}

	ps->arr[pos] = x;
	ps->size++;
}

void SLErase(SL* ps, int pos)
{
	assert(ps != NULL);
	assert(pos >= 0 && pos < ps->size);

	for (int i = pos; i < ps->size - 1; i++) {
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//int SLFind(SL* ps, SLDataType x)
//{
//	assert(ps != NULL);
//
//	for (int i = 0; i < ps->size; i++) {
//		if (ps->arr[i] == x) return i;
//	}
//
//	return -1;
//}

void SLDestroy(SL* ps)
{
	assert(ps != NULL);

	if (ps->arr) {
		free(ps->arr);
	}

	ps->arr = NULL;
	ps->capacity = ps->size = 0;
}

//void SLPrint(SL* ps)
//{
//	for (int i = 0; i < ps->size; i++) {
//		printf("%d ", ps->arr[i]);
//	}
//}